package cloud.keveri.base;

import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * <p>
 * 作者：沈自在
 **/
@Data
public class Result<T> implements Serializable {

    /**
     * 错误码
     */
    private Integer code;

    /**
     * 返回数据
     */
    private T data;

    /**
     * 错误提示，用户可阅读
     */
    private String msg;

    public Result(){}

    public Result(Integer code, String message){
        this.code = code;
        this.msg = message;
    }

    /**
     *
     */
    public static <T> Result<T> error(Result<?> result) {
        return error(result.getCode(), result.getMsg());
    }

    /**
     *
     */
    public static <T> Result<T> error(Integer code, String message) {
        if (GlobalErrorCodeConstants.SUCCESS.getCode().equals(code)){
            throw new IllegalArgumentException("code 必须是错误的");
        }
        Result<T> result = new Result<>();
        result.code = code;
        result.msg = message;
        return result;
    }

    /**
     *
     */
    public static <T> Result<T> error(ErrorCode errorCode) {
        return error(errorCode.getCode(), errorCode.getMessage());
    }

    /**
     *
     */
    public static <T> Result<T> ok(T data) {
        Result<T> result = new Result<>();
        result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
        result.data = data;
        result.msg = GlobalErrorCodeConstants.SUCCESS.getMessage();
        return result;
    }

    /**
     *
     */
    public static boolean isSuccess(Integer code) {
        return Objects.equals(code, GlobalErrorCodeConstants.SUCCESS.getCode());
    }

}
